//
//  LoginVC.m
//  ConvenientlyTake
//
//  Created by 张奇 on 2022/12/22.
//

#import "LoginVC.h"
#import "TGNetworkManager.h"
#import "TGPreviewFileView.h"
#import "AppDelegate+JPush.h"

@interface LoginVC ()

@property (weak, nonatomic) IBOutlet UIImageView *logoImgView;

@property (weak, nonatomic) IBOutlet UIView *phoneBgView;
@property (weak, nonatomic) IBOutlet UIView *passwordBgView;

@property (weak, nonatomic) IBOutlet QMUITextField *phoneTF;
@property (weak, nonatomic) IBOutlet QMUITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UILabel *tipLbel;

@property (weak, nonatomic) IBOutlet UIButton *secureBtn;

@property (weak, nonatomic) IBOutlet QMUIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *protocalBtn;

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorWhite;
    self.fd_prefersNavigationBarHidden = YES;
    self.navigationController.navigationBarHidden = YES;
    [self setupUI];
}

- (void)setupUI {
    //清除别名
    [AppDelegate deleteAlias];
    //重置app角标
    [AppDelegate setJPshBadgeWithBadge:0];
    
    self.phoneTF.maximumTextLength = 11;
    
    self.logoImgView.layer.cornerRadius = TableViewCornerRadius;
    self.logoImgView.layer.masksToBounds = YES;
    
    self.phoneBgView.layer.cornerRadius = 2;
    self.phoneBgView.layer.masksToBounds = YES;
    
    self.passwordBgView.layer.cornerRadius = 2;
    self.passwordBgView.layer.masksToBounds = YES;
    
    [self.secureBtn setImage:kImage(@"login_eye_close") forState:UIControlStateNormal];
    [self.secureBtn setImage:kImage(@"login_eye_open") forState:UIControlStateSelected];
    
    self.loginBtn.layer.cornerRadius = TableViewCornerRadius;
    self.loginBtn.layer.masksToBounds = YES;
    [self.protocalBtn setImage:kImage(@"nor_circle_icon") forState:UIControlStateNormal];
    [self.protocalBtn setImage:kImage(@"red_circle_icon") forState:UIControlStateSelected];
    
    [self.phoneTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.passwordTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
//    self.phoneTF.text = @"admin";
//    self.passwordTF.text = @"123456";
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    [self setNavStyleWhite];
}

- (IBAction)clickChangeEye:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.passwordTF.secureTextEntry = !sender.selected;
}


- (IBAction)clickLoginAction:(UIButton *)sender {
    if (EmptyCheck(self.phoneTF.text)) {
        [self.phoneTF becomeFirstResponder];
        [TGProgressHUD showHUDTip:@"请输入手机号"];
        return;
    }
    if (EmptyCheck(self.passwordTF.text)) {
        [self.passwordTF becomeFirstResponder];
        [TGProgressHUD showHUDTip:@"请输入密码"];
        return;
    }
    HidenKeybory;
//    if (!self.protocalBtn.selected) {
//        CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
//        shake.fromValue = [NSNumber numberWithFloat:-5];
//        shake.toValue = [NSNumber numberWithFloat:5];
//        shake.duration = 0.1;//执行时间
//        shake.autoreverses = YES;//是否重复
//        shake.repeatCount = 3;//次数
//        [self.protocalBtn.layer addAnimation:shake forKey:@"shakeAnimation"];
//        [self.protocalBtn.layer addAnimation:shake forKey:@"shakeAnimation"];
//        [TGProgressHUD showHUDTip:@"请勾选用户协议及隐私政策"];
//        WEAK
//        [TGLEEAlert alertReigsterAgreementSuccessClick:^{
//            STRONG
//            self.protocalBtn.selected = YES;
//            [self loginPassAction];
//        }];
//    } else {
        [self loginPassAction];
//    }
}
///使用密码登录
- (void)loginPassAction {
    [TGProgressHUD showHUD:@"登录中..."];
    NSString *url = APP_URL;
//    NSString *testUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"testUrl"];
//    if (!EmptyCheck(testUrl)) {
//        url = testUrl;
//    }
    
    [TGNetworkManager startRequestWithURL:[NSString stringWithFormat:@"%@api/login", url] method:@"POST" paramters:@{@"username": _phoneTF.text, @"password": _passwordTF.text, @"rememberMe": @"true"} success:^(TGResponseItem *responseItem) {
        NSLog(@"---%@", responseItem);
        [TGGCD executeMainAsyncTask:^{
            [TGProgressHUD dismissMPHUD];
            if (responseItem.success) {
                self.tipLbel.hidden = YES;
                TGUserModel *userModel = [TGUserModel modelWithJSON:responseItem.data];
                userModel.getAliasSeq = [self getTimestamp];//存储别名序列号
                [TGUserModel save:userModel];
                [self loginSuccess];
            } else {
//                [TGProgressHUD showHUDTip:R(responseItem.message)];
                self.tipLbel.hidden = NO;
            }
            if (responseItem.status == 406) {
                [self clickChangeEye:self.secureBtn];
            }
        }];
    } failure:^(NSError *error) {
        [TGProgressHUD showHUDTipNetError];
    }];

}

- (void)loginSuccess {
    NSLog(@"登录更换了用户id = %@",[TGUserModel getUserEntity].userId);
    //设置别名
    [AppDelegate setAlias:[TGUserModel getUserEntity].userId];
    
    [self dismissViewControllerAnimated:YES completion:^{
       
        [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationWithLogInRefreshData object:nil];
        
        if (self.complentBlock) {
            self.complentBlock();
        }
    
    }];
}

- (IBAction)clickProtocolAction:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (IBAction)clickShowProtocal:(UIButton *)sender {
    TGPreviewFileView *previeView = [[TGPreviewFileView alloc] initWithTitle:@"《随手拍用户服务协议》" height:SCREEN_HEIGHT];
    previeView.linkStr = AgreementURL;
    [previeView show];
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    self.tipLbel.hidden = YES;
}

//取时间戳设置推送别名序列号
-(NSInteger)getTimestamp
{
    NSString *timestamp = [NSString df_getCurrentTimestamp];
    NSString *time = [timestamp substringFromIndex:timestamp.length- 6];
    return [time integerValue];
    
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

@end
